package com.xnyzc.lhy.mis.service.impl.citymanage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.mis.entity.area.OaSysArea;
import com.xnyzc.lhy.mis.entity.area.OaSysOpenArea;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.param.cms.PageVo;
import com.xnyzc.lhy.mis.entity.param.cms.city.CityParam;
import com.xnyzc.lhy.mis.entity.result.area.OaSysOpenAreaResult;
import com.xnyzc.lhy.mis.entity.result.cms.role.UserLevelResult;
import com.xnyzc.lhy.mis.mapper.area.OaSysAreaMapper;
import com.xnyzc.lhy.mis.mapper.area.OaSysOpenAreaMapper;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.service.cms.citymanage.CityManageService;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 城市管理接口实现类
 *
 * @author zhaolijie
 * @date 2019/08/29
 */
@Service
public class CityManageServiceImpl implements CityManageService {


    @Autowired
    private OaSysAreaMapper oaSysAreaMapper;

    @Autowired
    private OaSysOpenAreaMapper oaSysOpenAreaMapper;

    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    /**
     * 获取所有城市
     *
     * @return
     */
    @Override
    public Rv getAllCity() {
        //查询城市
        List<HashMap<String, Object>> allCityGroup = oaSysAreaMapper.allCityGroup();
        //查询非城市
        List<HashMap<String, Object>> allCityChild = oaSysAreaMapper.allCityChild();
        // 将拼接完毕的菜单放入resultList返回
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (int i = 0; i < allCityGroup.size(); i++) {
            HashMap<String, Object> allCityGroupHashMap = allCityGroup.get(i);
            List<Map<String, Object>> child_list = new ArrayList<>();
            allCityGroupHashMap.put("label", allCityGroupHashMap.get("name"));
            allCityGroupHashMap.put("value", allCityGroupHashMap.get("area_id"));
            for (int j = 0; j < allCityChild.size(); j++) {
                HashMap<String, Object> allCityChildHashMap = allCityChild.get(j);
                if (String.valueOf(allCityGroupHashMap.get("area_id")).equals(allCityChildHashMap.get("parent_id"))) {
                    child_list.add(allCityChildHashMap);
                }
                allCityChildHashMap.put("label", allCityChildHashMap.get("name"));
                allCityChildHashMap.put("value", allCityChildHashMap.get("area_id"));
            }
            allCityGroupHashMap.put("children", child_list);
            resultList.add(allCityGroupHashMap);
        }
        return Rv.wrap(EErrorCode.success, resultList);
    }

    /**
     * 查询开通城市
     *
     * @param current：当前页
     * @return
     */
    @Override
    public Rv getOpenAreaList(Integer current) {
        String tag = TokenUtil.getTag();
        if (CheckUtil.objIsEmpty(tag)) {
            throw PangException.create(EErrorCode.missingAuthArgs);
        }
        IPage iPage = new Page();
        iPage.setCurrent(current);
        iPage.setSize(20);
        QueryWrapper<OaSysOpenArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysOpenArea.TAG, tag);
        queryWrapper.orderByDesc(OaSysOpenArea.CREATE_TIME);
        IPage<OaSysOpenArea> areaList = oaSysOpenAreaMapper.selectPage(iPage, queryWrapper);
        List<OaSysOpenAreaResult> resultsList = new ArrayList<>();
        PageVo pageVo = new PageVo();
        pageVo.setItems(resultsList);
        pageVo.setTotal(0L);
        List<OaSysDict> leveDictlList = getLevelDictList();
        resultsList = getDisposalData(leveDictlList, resultsList, areaList.getRecords());
        pageVo.setItems(resultsList);
        pageVo.setTotal(areaList.getTotal());
        return Rv.wrap(EErrorCode.success, pageVo);
    }

    private List<OaSysDict> getLevelDictList() {
        QueryWrapper<OaSysDict> queryLevelDict = new QueryWrapper<>();
        queryLevelDict.eq(OaSysDict.TYPE, "require_level");
        return oaSysDictMapper.selectList(queryLevelDict);
    }

    public List<OaSysOpenAreaResult> getDisposalData(List<OaSysDict> leveDictlList, List<OaSysOpenAreaResult> resultsList, List<OaSysOpenArea> areaList) {
        //OaSysOpenAreaResult result=new OaSysOpenAreaResult();
        for (OaSysOpenArea area : areaList) {
            // result = new OaSysOpenAreaResult();
            OaSysOpenAreaResult result = new OaSysOpenAreaResult();
            result.setCityId(area.getCityId());
            result.setCityName(area.getCityName());
            result.setCityPyname(area.getCityPyname());
            result.setIsOpne(area.getIsOpne());
            result.setIsThirdParty(area.getIsThirdParty());
            result.setOpenAreaId(area.getOpenAreaId());
            result.setProvinceId(area.getProvinceId());
            result.setProvinceName(area.getProvinceName());
            if (CheckUtil.objIsNotEmpty(area.getBusinessType())) {
                List<String> moduleIdList = new ArrayList<>();
                String[] modules = area.getBusinessType().split(",");
                for (String m : modules) {
                    moduleIdList.add(m);
                }
                result.setBusinessTypeList(moduleIdList);
            }
            resultsList.add(result);
        }
        for (OaSysOpenAreaResult results : resultsList) {
            String businessType = "";
            results.setBusinessType(businessType);
            if (CheckUtil.objIsNotEmpty(results.getBusinessTypeList())) {
                for (String level : results.getBusinessTypeList()) {
                    for (OaSysDict dict : leveDictlList) {
                        if (level.equals(dict.getValue())) {
                            if (CheckUtil.objIsEmpty(businessType)) {
                                businessType = dict.getLabel() + ",";
                            } else {
                                businessType = businessType + dict.getLabel() + ",";
                            }
                        }
                    }
                }
                if (CheckUtil.objIsNotEmpty(businessType)) {
                    results.setBusinessType(businessType.substring(0, businessType.length() - 1));
                }
            }
        }
        return resultsList;
    }

    /**
     * 模糊查询开通城市
     *
     * @param current：查询页
     * @param areaId：区域表主键ID
     * @param isOpne：0-未开通。1-开通
     * @return
     */
    @Override
    public Rv getOpenAreaListLike(Integer current, Long areaId, Integer isOpne) {
        List<OaSysDict> leveDictlList = getLevelDictList();
        IPage<OaSysOpenArea> areaList = null;
        IPage iPage = new Page();
        iPage.setCurrent(current);
        iPage.setSize(20);
        if (null != areaId && null != isOpne) {
            //都不为空时
            QueryWrapper<OaSysArea> queryWrapperArea = new QueryWrapper<>();
            queryWrapperArea.eq(OaSysArea.AREA_ID, areaId);
            OaSysArea oaSysArea = oaSysAreaMapper.selectOne(queryWrapperArea);
            QueryWrapper<OaSysOpenArea> queryWrapperOpenArea = new QueryWrapper<>();
            queryWrapperOpenArea.eq(OaSysOpenArea.PROVINCE_ID, oaSysArea.getParentId());
            queryWrapperOpenArea.eq(OaSysOpenArea.IS_OPNE, isOpne);
            queryWrapperOpenArea.orderByDesc(OaSysOpenArea.CREATE_TIME);
            areaList = oaSysOpenAreaMapper.selectPage(iPage, queryWrapperOpenArea);
        } else if (null == areaId && null != isOpne) {
            //选择开通状态不选择城市
            QueryWrapper<OaSysOpenArea> queryWrapperOpenArea = new QueryWrapper<>();
            queryWrapperOpenArea.eq(OaSysOpenArea.IS_OPNE, isOpne);
            queryWrapperOpenArea.orderByDesc(OaSysOpenArea.CREATE_TIME);
            areaList = oaSysOpenAreaMapper.selectPage(iPage, queryWrapperOpenArea);
        } else {
            //选择城市不选择开通状态
            QueryWrapper<OaSysArea> queryWrapperArea = new QueryWrapper<>();
            queryWrapperArea.eq(OaSysArea.AREA_ID, areaId);
            OaSysArea oaSysArea = oaSysAreaMapper.selectOne(queryWrapperArea);
            QueryWrapper<OaSysOpenArea> queryWrapperOpenArea = new QueryWrapper<>();
            queryWrapperOpenArea.eq(OaSysOpenArea.PROVINCE_ID, oaSysArea.getParentId());
            queryWrapperOpenArea.orderByDesc(OaSysOpenArea.CREATE_TIME);
            areaList = oaSysOpenAreaMapper.selectPage(iPage, queryWrapperOpenArea);
        }
        List<OaSysOpenAreaResult> resultsList = new ArrayList<>();
        PageVo pageVo = new PageVo();
        pageVo.setItems(resultsList);
        pageVo.setTotal(0L);
        if (CheckUtil.objIsNotEmpty(areaList)) {
            resultsList = getDisposalData(leveDictlList, resultsList, areaList.getRecords());
        }
        pageVo.setItems(resultsList);
        pageVo.setTotal(areaList.getTotal());
        return Rv.wrap(EErrorCode.success, pageVo);
    }


    /**
     * 修改状态
     *
     * @param open_area_id：主键
     * @param isOpne：状态0-未开通。1-开通
     * @return
     */
    @Override
    public Rv updateisOpne(Long open_area_id, Integer isOpne) {
        OaSysOpenArea oaSysOpenArea = new OaSysOpenArea();
        oaSysOpenArea.setOpenAreaId(open_area_id);
        oaSysOpenArea.setIsOpne(isOpne);
        oaSysOpenAreaMapper.updateById(oaSysOpenArea);
        return Rv.wrap(EErrorCode.success);
    }

    /**
     * 添加城市
     *
     * @return
     */
    @Override
    public Rv addCity(CityParam param) {
        String tag = TokenUtil.getTag();
        if (CheckUtil.objIsEmpty(tag, param.getAreaId(), param.getIsOpne())) {
            throw PangException.create(EErrorCode.missingAuthArgs);
        }
        //查询子
        QueryWrapper<OaSysArea> queryWrapperChild = new QueryWrapper<>();
        queryWrapperChild.eq(OaSysArea.AREA_ID, param.getAreaId());
        OaSysArea oaSysAreaChild = oaSysAreaMapper.selectOne(queryWrapperChild);
        //查询父
        QueryWrapper<OaSysArea> queryWrapperGroup = new QueryWrapper<>();
        queryWrapperGroup.eq(OaSysArea.AREA_ID, oaSysAreaChild.getParentId());
        OaSysArea oaSysAreaGroup = oaSysAreaMapper.selectOne(queryWrapperGroup);
        //查询该城市是否已经添加
        QueryWrapper<OaSysOpenArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysOpenArea.CITY_ID, oaSysAreaChild.getAdCode());
        List<OaSysOpenArea> oaSysOpenAreas = oaSysOpenAreaMapper.selectList(queryWrapper);
        if (oaSysOpenAreas.size() == 0) {
            OaSysOpenArea oaSysOpenArea = new OaSysOpenArea();
            oaSysOpenArea.setBusinessType(Joiner.on(",").join(param.getBusinessTypeList()));
            oaSysOpenArea.setOpenAreaId(IDUtil.nextId());
            oaSysOpenArea.setProvinceId(String.valueOf(oaSysAreaGroup.getAreaId()));
            oaSysOpenArea.setProvinceName(oaSysAreaGroup.getName());
            oaSysOpenArea.setCityId(oaSysAreaChild.getAdCode());
            oaSysOpenArea.setCityName(oaSysAreaChild.getName());
            oaSysOpenArea.setCityPyname(this.convertChineseToFullSpell(oaSysAreaChild.getName()));
            oaSysOpenArea.setIsOpne(param.getIsOpne());
            oaSysOpenArea.setTag(tag);
            oaSysOpenArea.setCreateUser(TokenUtil.getTokenUserId());
            oaSysOpenArea.setCreateTime(new Date());
            oaSysOpenArea.setUpdateTime(new Date());
            oaSysOpenAreaMapper.insert(oaSysOpenArea);
            return Rv.wrap(EErrorCode.success);
        } else {
            return Rv.wrap(EErrorCode.beUsed);
        }
    }

    /**
     * 开通城市关联详情
     *
     * @return
     */
    @Override
    public Rv getCityDetails(CityParam param) {
        if (CheckUtil.objIsEmpty(param.getOpenAreaId())) {
            throw PangException.create(EErrorCode.missingAuthArgs);
        }
        OaSysOpenArea openArea = oaSysOpenAreaMapper.selectById(param.getOpenAreaId());
        List<UserLevelResult> levelResult = new ArrayList<>();
        UserLevelResult result = new UserLevelResult();
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "require_level");
        List<OaSysDict> oaSysDictList = oaSysDictMapper.selectList(queryWrapper);
        if (CheckUtil.objIsNotEmpty(openArea) && CheckUtil.objIsNotEmpty(openArea.getBusinessType())) {
            String[] types = openArea.getBusinessType().split(",");
            for (OaSysDict all : oaSysDictList) {
                result = new UserLevelResult();
                result.setSelected(0);
                result.setName(all.getLabel());
                result.setValue(all.getValue());
                for (String type : types) {
                    if (all.getValue().equals(type)) {
                        result.setSelected(1);
                    }
                }
                levelResult.add(result);
            }
        } else {
            for (OaSysDict all : oaSysDictList) {
                result = new UserLevelResult();
                result.setValue(all.getValue());
                result.setSelected(0);
                result.setName(all.getLabel());
                levelResult.add(result);
            }
        }
        return Rv.wrap(EErrorCode.success, levelResult);
    }

    /**
     * 修改城市关联
     *
     * @return
     */
    @Override
    public Rv getCityRelevance(CityParam param) {
        if (CheckUtil.objIsEmpty(param.getOpenAreaId())) {
            throw PangException.create(EErrorCode.missingAuthArgs);
        }
        OaSysOpenArea openArea = oaSysOpenAreaMapper.selectById(param.getOpenAreaId());
        openArea.setUpdateTime(new Date());
        openArea.setUpdateUser(TokenUtil.getTokenUserId());
        openArea.setBusinessType(Joiner.on(",").join(param.getBusinessTypeList()));
        oaSysOpenAreaMapper.updateById(openArea);
        return Rv.wrap(EErrorCode.success);
    }

    @Override
    public Rv getAllUsedCity() {
        List<OaSysArea> allUsedCity = oaSysAreaMapper.getAllUsedCity();
        return Rv.wrap(allUsedCity);
    }


    /**
     * 汉字转换成汉语拼音全拼，英文字符不变
     *
     * @param chinese 汉字
     * @return 拼音
     * @author you chou
     */
    public String convertChineseToFullSpell(String chinese) {
        String CHINESE_PATTERN = "[\u4e00-\u9fa5]";
        String pinyinName = "";
        char[] nameChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        for (int i = 0; i < nameChar.length; i++) {
            if (Pattern.matches(CHINESE_PATTERN, nameChar[i] + "")) {
                try {
                    pinyinName += PinyinHelper.toHanyuPinyinStringArray(
                            nameChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    throw PangException.create(EErrorCode.dataParseError);
                }
            } else {
                pinyinName += nameChar[i];
            }
        }
        return pinyinName;
    }


}
